
package com.naza.rpc.spring;

import com.naza.rpc.filter.Filter;
import com.naza.rpc.filter.ServiceFilterBinder;
import com.naza.rpc.netty.RpcReceiveExecutor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * server端xml对应的server标签对应的处理类
 * 
 * @author yl
 */
public class Service implements ApplicationContextAware {
    // naza:service 中的interfaceName
    private String interfaceName;

    // naza:service中的ref
    private String ref;

    // naza:service中的filter
    private String filter;

    private ApplicationContext applicationContext;

    /**
     * *
     * RpcReceiveExecutor.start方法是在Registery的bean初始化(afterPropertiesSet)时做的，因此要保证MessageRecvExecutor中的HandlerMap要已经初始化,
     * 而本方法也是在所有bean创建之后(未执行初始化afterPropertiesSet)才执行
     * 
     * ApplicationContextAware的回调是在afterPropertiesSet之后执行
     * 
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        // applicationContext.publishEvent(new ServerStartEvent(new Object()));
        ServiceFilterBinder binder = new ServiceFilterBinder();
        System.out.println(ref);
        if (StringUtils.isBlank(filter) || !(applicationContext.getBean(filter) instanceof Filter)) {
            // 判断service的定义中是否有filter
            binder.setObject(applicationContext.getBean(ref));
        } else {
            binder.setObject(applicationContext.getBean(ref));
            binder.setFilter((Filter) applicationContext.getBean(filter));
        }

        RpcReceiveExecutor.getInstance().getHandlerMap().put(interfaceName, binder);
        
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public String getFilter() {
        return filter;
    }

    public void setFilter(String filter) {
        this.filter = filter;
    }

    public String getRef() {
        return ref;
    }

    public void setRef(String ref) {
        this.ref = ref;
    }

    public String getInterfaceName() {
        return interfaceName;
    }

    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
    }
}
